import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/userInfo")
public class userInfoServlet extends HttpServlet {
    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果有userId则证明是从详情页进入
        String blogId=req.getParameter("blogId");
        if(blogId==null){
            userInfoFromList(req,resp);
        }else {
            userInfoFromContent(req,resp,blogId);
        }
    }

    private void userInfoFromContent(HttpServletRequest req, HttpServletResponse resp, String blogId) throws IOException {
        //先查找博客列表
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectById(Integer.parseInt(blogId));
        if(blog==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("博客不存在");
            return;
        }
        //再查找用户列表
        UserDao userDao=new UserDao();
        User user=userDao.selectById(blog.getUserId());
        //防止库中没有此用户
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户不存在");
            return;
        }
        //密码置空，
        user.setPassword("");
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));

    }

    private void userInfoFromList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session=req.getSession();
        if(session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        User user= (User) session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        user.setPassword("");
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
